package com.ringtheweb.model;


import static javax.persistence.GenerationType.*;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Version;

import org.hibernate.validator.Length;


/**
 * A role
 * @author ldewavri
 *
 */

@Table(name = "ROLES")
@NamedQueries({
    @NamedQuery(name="rolesByName",
        query="SELECT r FROM Role as r WHERE r.name = :name")
})
@Entity
public class Role implements Serializable,Comparable<Role> {
	
    /**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	@Id
    @GeneratedValue(strategy = AUTO)
    @Column(name = "ROLE_ID")
    private Long id = null;

    @Version
    @Column(name = "OBJ_VERSION")
    private int version = 0;

    @Column(name = "NAME", length = 255, nullable = false, unique = true)
    private String name;

    @Column(name = "DISPLAY_NAME", length = 255, nullable = false, unique = true)
    @Length(min = 3, max = 40)
    private String displayName;
    

    @Column(name = "CREATED_ON", nullable = false, updatable = false)
    private Date createdOn = new Date();
    
    
    private Role(){};

    public Role(String name) {
    	this.name = name;
    }

    public Role(String name, String displayName) {
        this.name = name;
        this.displayName = displayName;
    }

    // Immutable properties
    public Long getId() { return id; }
    public Integer getVersion() { return version; }
    public Date getCreatedOn() { return createdOn; }

    // Mutable properties
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getDisplayName() { return displayName; }
    public void setDisplayName(String displayName) { this.displayName = displayName; }

    @Override
    public String toString() {
        return  "Role ('" + getId() + "'), " +
                "Name: '" + getName() + "'";
    }
    

    @Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (!(obj instanceof Role)) {
			return false;
		}

		Role role=(Role)obj;
		return (this.name == null? role.getName() == null :
			this.name.equals(role.getName()));
	}

	@Override
	public int hashCode() {
		int result=17;
		return result + 31* (name == null ? 
				0 : name.hashCode());
	}


	@Override
	public int compareTo(Role role) {
		if (role == null) {
			return name == null ? 0 : -1;
		}
		if (name == null) {
			return role.getName() == null ? 0 : 1;
		}
		return getName().compareTo(role.getName());
	}

}
